﻿using IH.Comm.Dtos;
using IH.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using NAutowired.Core.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace IH.Apis.Filters
{
    public class TokenAuthAttribute : ActionFilterAttribute
    {
        private readonly UserService _userService;

        public TokenAuthAttribute(UserService userService)
        {
            _userService = userService;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Filters.Any(a => a is SkipAuthAttribute))
            {
                return;
            }

            var token = context.HttpContext.Request.Headers["token"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                HandleTokenAsync(context.HttpContext, token).Wait();
            }
            else
            {
                throw new UnauthorizedAccessException("缺少token");
            }
        }

        private async Task HandleTokenAsync(HttpContext httpContext, string token)
        {
            var userInfo = await _userService.GetUserByTokenAsync(token);
            if (userInfo == null)
            {
                throw new UnauthorizedAccessException("token错误");
            }
            var claims = new List<Claim>()
            {
                new Claim(nameof(AppUser.Token),token),
                new Claim(nameof(AppUser.Name),userInfo.HeadPic),
                new Claim(nameof(AppUser.UserId),userInfo.UserId),
                new Claim(nameof(AppUser.HeadPic),userInfo.HeadPic),
            };
            httpContext.User.AddIdentity(new ClaimsIdentity(claims));
        }
    }

}
